﻿using System;
using System.Configuration;
using System.IO;
using CN2P.ServiceModel;
using CN2P.ServiceModel.ServiceClients;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;

namespace CN2P.ImportTool
{
    public class Program
    {
        private static readonly ECommerceServiceClient serviceClient = new ECommerceServiceClient(ECommerceServiceClientConfiguration.FromAppConfig());

        static void Main(string[] args)
        {
            while (true)
            {
                Console.Clear();
                Console.WriteLine("1. Import Products");
                Console.WriteLine("2. Import Recommendations");
                Console.WriteLine("3. Import Carts");
                Console.WriteLine("4. Import All");

                Console.WriteLine("5. Delete All");
                Console.WriteLine("6. Delete All Orders");
                Console.WriteLine("7. Delete All Carts");
                Console.WriteLine("8. Delete All Products");
                Console.WriteLine("9. Delete All Recommendations");

                Console.WriteLine("i. Import images");
                Console.WriteLine();
                Console.WriteLine("0. Exit");
                Console.WriteLine();

                try
                {
                    var key = Console.ReadKey(true);
                    switch (key.KeyChar)
                    {
                        case '1':
                            ImportProducts();
                            break;
                        case '2':
                            ImportRecommendations();
                            break;
                        case '3':
                            ImportCarts();
                            break;
                        case '4':
                            ImportAll();
                            break;
                        case '5':
                            DeleteAll();
                            break;
                        case '6':
                            DeleteAllOrders();
                            break;
                        case '7':
                            DeleteAllCarts();
                            break;
                        case '8':
                            DeleteAllProducts();
                            break;
                        case '9':
                            DeleteRecommends();
                            break;
                        case 'i':
                            ImportImages();
                            break;
                        case '0':
                            return;
                    }
                }
                catch (Exception exc)
                {
                    Console.WriteLine(exc.Message);
                }
                Console.WriteLine("Presss any key");
                Console.ReadKey();
            }
        }

        private static void ImportImages()
        {
            Console.WriteLine("Importing images");
            var dir = ConfigurationManager.AppSettings["ImportDir"];
            dir = Path.Combine(dir, "Images");

            var cs = ConfigurationManager.AppSettings["BlobConnectionString"];
            CloudStorageAccount account = CloudStorageAccount.Parse(cs);
            CloudBlobClient blobClient = account.CreateCloudBlobClient();
            CloudBlobContainer cnt = blobClient.GetContainerReference(ConfigurationManager.AppSettings["BlobContainer"]);
            cnt.CreateIfNotExists();

            foreach (var file in new DirectoryInfo(dir).GetFiles())
            {
                Console.WriteLine("Importing image: {0}", file.Name);
                ImportImage(cnt, file.FullName);

            }
        }

        private static void ImportImage(CloudBlobContainer container, string fullPath)
        {
            var blob = container.GetBlockBlobReference(Path.GetFileName(fullPath));
            using (var stream = File.Open(fullPath, FileMode.Open))
            {
                blob.UploadFromStream(stream);
            }
        }

        private static void ImportAll()
        {
            ImportProducts();
            ImportRecommendations();
            ImportCarts();
        }

        private static void ImportRecommendations()
        {
            Console.WriteLine("Importing recommendations");
            var dir = ConfigurationManager.AppSettings["ImportDir"];
            dir = Path.Combine(dir, "Recommendations");
            foreach (var file in new DirectoryInfo(dir).GetFiles("*.json"))
            {
                Console.WriteLine("Importing recommendations: {0}", file.Name);
                var content = new StreamReader(file.FullName).ReadToEnd();
                serviceClient.RecommendationsService.AddTraversal(content);
            }

            Console.WriteLine("All recommendations have been imported");
        }

        private static void ImportProducts()
        {
            Console.WriteLine("Importing products");
            var dir = ConfigurationManager.AppSettings["ImportDir"];
            dir = Path.Combine(dir, "Products");

            var imageBaseUrl = ConfigurationManager.AppSettings["ImageBaseUrl"];
            if (imageBaseUrl.EndsWith("/"))
            {
                imageBaseUrl = imageBaseUrl.Substring(0, imageBaseUrl.Length - 1);
            }

            foreach (var file in new DirectoryInfo(dir).GetFiles("*.json"))
            {
                Console.WriteLine("Importing product: {0}", file.Name);
                var content = new StreamReader(file.FullName).ReadToEnd();

                var prod = FullProductModel.FromJson(content);

                if (!prod.ImageUrl.StartsWith("/"))
                {
                    prod.ImageUrl = "/" + prod.ImageUrl;
                }

                prod.ImageUrl = (imageBaseUrl + prod.ImageUrl).ToLowerInvariant();
                serviceClient.ProductsService.CreateProduct(prod);
            }

            Console.WriteLine("All products have been imported");
        }

        private static void ImportCarts()
        {
            Console.WriteLine("Importing carts");
            var dir = ConfigurationManager.AppSettings["ImportDir"];
            dir = Path.Combine(dir, "Carts");
            foreach (var file in new DirectoryInfo(dir).GetFiles("*.json"))
            {
                Console.WriteLine("Importing cart: {0}", file.Name);
                var content = new StreamReader(file.FullName).ReadToEnd();
                serviceClient.CartService.AddCart(Path.GetFileNameWithoutExtension(file.Name), content);
            }

            Console.WriteLine("All carts have been imported");
        }

        private static void DeleteAll()
        {
            Console.WriteLine("Type OK if you are sure you want to delete everything.");
            var line = Console.ReadLine();
            if (line == "OK")
            {
                serviceClient.ProductsService.DeleteAll();
                serviceClient.RecommendationsService.DeleteAll();
                serviceClient.CartService.DeleteAll();
                serviceClient.OrdersService.DeleteAll();
            }
        }

        private static void DeleteAllProducts()
        {
            Console.WriteLine("Type OK if you are sure you want to delete all products.");
            var line = Console.ReadLine();
            if (line == "OK")
            {
                serviceClient.ProductsService.DeleteAll();
            }
        }

        private static void DeleteAllOrders()
        {
            Console.WriteLine("Type OK if you are sure you want to delete all orders.");
            var line = Console.ReadLine();
            if (line == "OK")
            {
                serviceClient.OrdersService.DeleteAll();
            }
        }

        private static void DeleteAllCarts()
        {
            Console.WriteLine("Type OK if you are sure you want to delete all carts.");
            var line = Console.ReadLine();
            if (line == "OK")
            {
                serviceClient.CartService.DeleteAll();
            }
        }

        private static void DeleteRecommends()
        {
            Console.WriteLine("Type OK if you are sure you want to delete all recommendations.");
            var line = Console.ReadLine();
            if (line == "OK")
            {
                serviceClient.RecommendationsService.DeleteAll();
            }
        }
    }
}
